/**
 * 详情界面
 */
package net.youpo.Market.UI.AppInfo;

import java.io.File;
import java.lang.ref.SoftReference;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import net.youpo.Market.R;
import net.youpo.Market.Bean.AppInfoBean;
import net.youpo.Market.Bean.ScreenshotBean;
import net.youpo.Market.Download.DownloadManager;
import net.youpo.Market.Download.Downloads;
import net.youpo.Market.Net.HttpConnection;
import net.youpo.Market.Util.ConstantsTable;
import net.youpo.Market.Util.Tools;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Layout;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class InfoActivity extends Activity {
	private final int REFRESH_LIST = 516;
	private final int REFRESH_TIME = 200;// 刷新间隔
	private boolean mDownloadFlag = true;
	private boolean detailFlag = false;
	private Gallery mAppGalery;
	private TextView mAppVersion;
	private TextView mAppSize;
	private TextView mAppDesc;
	private TextView mAppLan;
	private TextView mAppAutho;
	private Button mDownloadBtn;
	private Button mFavoritesBtn;
	private GalleryAdapter mAdapter;
	private DownloadManager mDownloadManager;
	private AppInfoBean mAppBean = new AppInfoBean();
	private BlockingQueue<Runnable> mBlockingQueue = new LinkedBlockingQueue<Runnable>();// 创建线程队列
	private ThreadPoolExecutor mExecutor = new ThreadPoolExecutor(1, 10, 30,
			TimeUnit.SECONDS, mBlockingQueue);// 创建线程池,线程大小1,最大池大小10,线程持续时间30,持续时间单位s，线程队列

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mAppBean = (AppInfoBean) getIntent().getSerializableExtra(
				ConstantsTable.KEY_VC);
		setContentView(R.layout.info_activity);
		this.mDownloadManager = new DownloadManager(this);
		initUI();
	}

	private void initUI() {
		mAppVersion = (TextView) findViewById(R.id.appinfo_version_tv);
		mAppSize = (TextView) findViewById(R.id.appinfo_size_tv);
		mAppLan = (TextView) findViewById(R.id.appinfo_lan_tv);
		mAppAutho = (TextView) findViewById(R.id.appinfo_autho_tv);
		mAppDesc = (TextView) findViewById(R.id.appinfo_desc_tv);
		mDownloadBtn = (Button) findViewById(R.id.appinfo_download_btn);
		mFavoritesBtn = (Button) findViewById(R.id.appinfo_favorites_btn);
		mAppVersion.setText(mAppBean.APP_VER_NAME);
		mAppSize.setText(mAppBean.APP_SIZE);
		mAppLan.setText(mAppBean.APP_LANGUAGE);
		mAppAutho.setText(mAppBean.APP_AUTHOR);
		mAppDesc.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (detailFlag) {
					mAppDesc.setText("------------点击展开显示----------");
					mAppDesc.setGravity(Gravity.CENTER_HORIZONTAL);
					detailFlag = false;
				} else {
					mAppDesc.setText(mAppBean.APP_DESC);
					mAppDesc.setGravity(Gravity.LEFT);
					detailFlag = true;
				}
			}
		});

		mDownloadBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (mDownloadFlag) {
					Toast.makeText(InfoActivity.this, "开始下载",
							Toast.LENGTH_SHORT).show();
					mDownloadManager.insertDownload(mAppBean,
							Downloads.TYPE_DOWNLOAD);
					mDownloadFlag = false;
				} else {
					Toast.makeText(InfoActivity.this, "已经开始下载,请耐心等候",
							Toast.LENGTH_SHORT).show();
				}

			}
		});

		mFavoritesBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
//				Toast.makeText(InfoActivity.this, mAppBean.APP_NAME, 1000)
//						.show();
				InfoActivity.this.finish();
			}
		});

		mAppGalery = (Gallery) findViewById(R.id.appinfo_gallery);

		mAdapter = new GalleryAdapter(this, mAppBean);
		mAppGalery.setAdapter(mAdapter);
		mAppGalery.scrollTo(50, 0);
		mAppGalery.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// Log.d("H3c", position + "...");
				Intent intent = new Intent(InfoActivity.this,
						FullScreenPictureActivity.class);
				int length = mAppBean.SCREENSHOT.length;
				String[] imageArr = new String[length];
				for (int n = 0; n < length; n++) {
					try {
						imageArr[n] = mAppBean.SCREENSHOT[n].IMAGE;
					} catch (Exception e) {
						Log.e("H3c", "null point");
						return;
					}
				}
				Bundle b = new Bundle();
				b.putStringArray(ConstantsTable.KEY_PS, imageArr);
				intent.putExtras(b);
				intent.putExtra(ConstantsTable.KEY_APPID, mAppBean.APP_ID);
				intent.putExtra(ConstantsTable.GALLERY_POSITION, position);
				startActivity(intent);
			}
		});
	}

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case REFRESH_LIST:
				mAdapter.notifyDataSetChanged();
				break;
			default:
			}

		}
	};

	private class GalleryAdapter extends BaseAdapter {
		private Context mContext;
		private ScreenshotBean[] mDataSource;
		private AppInfoBean mAppBean;

		public GalleryAdapter(Context ctx, AppInfoBean appBean) {
			this.mContext = ctx;
			this.mAppBean = appBean;
			this.mDataSource = appBean.SCREENSHOT;
		}

		@Override
		public int getCount() {
			if (mDataSource == null) {
				return 0;
			}
			return mDataSource.length;
		}

		@Override
		public Object getItem(int position) {
			return mDataSource[position];
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ImageView imageView;
			if (convertView == null) {
				imageView = new ImageView(mContext);
				imageView.setAdjustViewBounds(true);
				imageView.setPadding(8, 1, 8, 1);
				imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
			} else {
				imageView = (ImageView) convertView;
			}

			if (mDataSource != null
					&& mDataSource[position] != null
					&& (mDataSource[position].THUMB_BMP == null || mDataSource[position].THUMB_BMP
							.get() == null)) {
				imageView.setImageResource(R.drawable.loading);
				try {
					mBlockingQueue.put(new Runnable() {
						@Override
						public void run() {
							mHandler.removeMessages(REFRESH_LIST);
							File file = new File(ConstantsTable.CACHE_PATH
									+ "/" + mAppBean.APP_ID + "_THUMB_"
									+ position);
							Bitmap bmp = null;
							if (file.exists()) {// 如果有缓存文件
								bmp = Tools
										.getBitmapFromCache(ConstantsTable.CACHE_PATH
												+ "/"
												+ mAppBean.APP_ID
												+ "_THUMB_" + position);
							} else {// 没有缓存就从网络获取
								HttpConnection hc = new HttpConnection();

								bmp = hc.getNetworkBitmap(mDataSource[position].THUMB);

								Tools.saveBmpToSd(bmp, mAppBean.APP_ID
										+ "_THUMB_" + position);// 保存至缓存
							}
							SoftReference<Bitmap> sb = new SoftReference<Bitmap>(
									bmp);
							mDataSource[position].THUMB_BMP = sb;
							mHandler.sendEmptyMessageDelayed(REFRESH_LIST,
									REFRESH_TIME);
						}
					});
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				executeDownloadBitmapThread();

			} else {
				try {
					imageView.setImageBitmap(mDataSource[position].THUMB_BMP
							.get());
				} catch (Exception e) {
					Toast.makeText(mContext, "网络错误", 1000).show();
				}
			}
			return imageView;
		}
	}

	public void executeDownloadBitmapThread() {
		Runnable runnable = mBlockingQueue.poll();
		if (runnable != null) {
			try {
				mExecutor.execute(runnable);
			} catch (Exception e) {
				Log.e(ConstantsTable.LOG_TAG, "拒绝执行异常AppinfoActivity");
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mExecutor.shutdown();
		if (mAppBean.SCREENSHOT != null) {
			int length = mAppBean.SCREENSHOT.length;
			for (int n = 0; n < length; n++) {
				if (mAppBean.SCREENSHOT[n] != null
						&& mAppBean.SCREENSHOT[n].THUMB_BMP != null
						&& mAppBean.SCREENSHOT[n].THUMB_BMP.get() != null) {
					mAppBean.SCREENSHOT[n].THUMB_BMP.get().recycle();
					mAppBean.SCREENSHOT[n].THUMB_BMP = null;
				}
			}
		}
		if (mAppBean.APP_ICON_BMP != null) {
			Bitmap bitmap = ((BitmapDrawable) mAppBean.APP_ICON_BMP)
					.getBitmap();
			bitmap.recycle();
		}
	}
}
